package com.qumitech.visualnovel.service.trend.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.exception.BusinessException;
import com.qumitech.visualnovel.component.thirdapi.aliyun.AliYunOSSUtil;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.common.ResultEnum;
import com.qumitech.visualnovel.controller.vo.trend.*;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.trend.CommentAdminDTO;
import com.qumitech.visualnovel.pubdef.dto.trend.TrendAdminDTO;
import com.qumitech.visualnovel.pubdef.dto.trend.TwitterTopCfgAdminDTO;
import com.qumitech.visualnovel.pubdef.pubenum.AdminStateEnum;
import com.qumitech.visualnovel.service.exception.ExceptionService;
import com.qumitech.visualnovel.service.trend.TrendConfigService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: yilu
 * @Date: 2018/12/6 22:41
 * @Description:
 */

@Service
public class TrendCfgServiceImpl implements TrendConfigService {

    private final String CATEGORY_URL = "/trend/console/category";
    private final String CATEGORY_SORT_URL = "/trend/console/category/sort";
    private final String TOPIC_URL = "/trend/console/topic";
    private final String TOPIC_SORT_URL = "/trend/console/topic/sort";
    private final String ALL_TOPIC_URL = "/trend/console/all_topics";
    private final String HOT_TOPIC_URL = "/trend/console/topic/recommend";
    private final String HOT_TOPIC_SORT__URL = "/trend/console/topic/recommend/sort";
    private final String TREND_URL = "/trend/console/trend";
    private final String COMMENT_URL = "/trend/console/comment";
    private final String NUMBER_URL = "/num";
    private final String LIKE_URL = "/trend/console/like";
    private final String TREND_CONSOLE_URL = "/trend/console";
    //动态置顶
    private final String TWITTER_TOP_URL = "/admin/twitter/top";

    @Autowired
    private ExceptionService exceptionService;

    @Override
    public Map<String, Object> getCategories(Integer page, Integer size) {
        String url = UrlConstant.SERVER_URL + CATEGORY_URL;
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("page", page.toString());
        paramMap.put("size", size.toString());
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        if (rspMap.get("categories") == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rspMap;
    }

    @Override
    public Object getAllTopics() {
        String url = UrlConstant.SERVER_URL + ALL_TOPIC_URL;

        String body = HttpInvokeUtil.httpGet(url, null, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        return rsp.getData();
    }

    @Override
    public Map<String, Object> getTopicsByCategory(String categoryId) {
        String url = new StringBuilder(UrlConstant.SERVER_URL)
                .append(TOPIC_URL)
                .append("/")
                .append(categoryId)
                .toString();

        String body = HttpInvokeUtil.httpGet(url, null, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        if (rspMap.get("topic_list") == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rspMap;
    }

    @Override
    public void addCategory(TopicCategoryVO topicCategoryVO) {
        String url = UrlConstant.SERVER_URL + CATEGORY_URL;
        String req = JSONObject.toJSONString(topicCategoryVO);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void updateCategory(TopicCategoryVO topicCategoryVO) {
        String url = UrlConstant.SERVER_URL + CATEGORY_URL;
        String req = JSONObject.toJSONString(topicCategoryVO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void deleteCategory(String categoryId) {
        String url = UrlConstant.SERVER_URL + CATEGORY_URL;
        Map<String, String> headMap = new HashMap<>();
        headMap.put("category_id", categoryId);
        String body = HttpInvokeUtil.httpDelete(url, headMap);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void sortCategory(CategoryListVO categoryListVO) {
        String url = UrlConstant.SERVER_URL + CATEGORY_SORT_URL;

        String req = JSONObject.toJSONString(categoryListVO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void addTopic(TopicVO topicVO) {
        String url = UrlConstant.SERVER_URL + TOPIC_URL;
        String req = JSONObject.toJSONString(topicVO);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void deleteTopic(String topicId) {
        String url = UrlConstant.SERVER_URL + TOPIC_URL;
        Map<String, String> headMap = new HashMap<>();
        headMap.put("topic_id", topicId);
        String body = HttpInvokeUtil.httpDelete(url, headMap);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void updateTopic(TopicVO topicVO) {
        String url = UrlConstant.SERVER_URL + TOPIC_URL;
        String req = JSONObject.toJSONString(topicVO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void sortTopics(TopicListVO topicListVO, Boolean isHotTopic) {
        String url;
        if (isHotTopic) {
            url = UrlConstant.SERVER_URL + HOT_TOPIC_SORT__URL;
        } else {
            url = UrlConstant.SERVER_URL + TOPIC_SORT_URL;
        }

        String req = JSONObject.toJSONString(topicListVO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public BaseRsp listAllTopics(Map<String, String> paramMap) {
        String url = UrlConstant.SERVER_URL + TOPIC_URL;
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp baseRsp = JSON.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(baseRsp);
        return baseRsp;
    }

    @Override
    public Map<String, Object> getAllHotTopics() {
        String url = UrlConstant.SERVER_URL + HOT_TOPIC_URL;

        String body = HttpInvokeUtil.httpGet(url, null, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        if (rspMap.get("recommend_topics") == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rspMap;
    }

    @Override
    public void addHotTopic(List<HotTopicVO> hotTopicVO) {
        String url = UrlConstant.SERVER_URL + HOT_TOPIC_URL;
        String req = JSONObject.toJSONString(hotTopicVO);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void deleteHotTopic(String topicId) {
        String url = UrlConstant.SERVER_URL + HOT_TOPIC_URL;
        Map<String, String> headMap = new HashMap<>();
        headMap.put("topic_id", topicId);
        String body = HttpInvokeUtil.httpDelete(url, headMap);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public Map<String, Object> getTrendByConditions(Map<String, String> paramMap) {
        String url = UrlConstant.SERVER_URL + TREND_URL;
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();

        return rspMap;
    }

    @Override
    public void deleteTrend(List<String> trendIds) {
        String url = UrlConstant.SERVER_URL + TREND_URL;
        String body = HttpInvokeUtil.httpDeleteWithEntity(url, JSONObject.toJSON(trendIds).toString(), new HashMap<>(), UrlConstant.DefaultEncode);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public Map<String, Object> getComments(Map<String, String> paramMap) {
        String url = UrlConstant.SERVER_URL + COMMENT_URL;
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        return rspMap;
    }

    @Override
    public void deleteComment(String commentId) {
        String url = UrlConstant.SERVER_URL + COMMENT_URL + "/" + commentId;
        String body = HttpInvokeUtil.httpDelete(url, new HashMap<>());
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void addComment(CommentDTO dto) {
        String url = UrlConstant.SERVER_URL + COMMENT_URL;
        String req = JSONObject.toJSONString(dto);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    @Override
    public void updateTrendAdmin(TrendAdminDTO trendAdminDTO) {
        trendAdminDTO.setAdminer(getOperatorName());
        trendAdminDTO.setOperator(getOperatorName());
        String url = UrlConstant.SERVER_URL + TREND_URL;
        String req = JSONObject.toJSONString(trendAdminDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        if ((trendAdminDTO.getResourceUrl() != null && !trendAdminDTO.getResourceUrl().isEmpty()) && trendAdminDTO.getAdminState().equals(AdminStateEnum.DELETED.value())){
            List<String> newUrlList = new ArrayList<>();
            for (String resourceUrl : trendAdminDTO.getResourceUrl()){
                if (resourceUrl.contains(".gif")){
                    newUrlList.add(resourceUrl.substring(0, resourceUrl.indexOf(".gif")));
                }else if (resourceUrl.contains("_DURATION")){
                    newUrlList.add(resourceUrl.substring(0, resourceUrl.indexOf("_DURATION")));
                }else {
                    newUrlList.add(resourceUrl);
                }
            }
            if (newUrlList != null && !newUrlList.isEmpty()) {
                AliYunOSSUtil.deleteObjectList(newUrlList);
            }
        }
        if ((trendAdminDTO.getResourceUrl() != null && !trendAdminDTO.getResourceUrl().isEmpty()) && trendAdminDTO.getAdminState().equals(AdminStateEnum.DELETED.value())){
            List<String> newUrlList = new ArrayList<>();
            for (String resourceUrl : trendAdminDTO.getResourceUrl()){
                if (resourceUrl.contains(".gif")){
                    newUrlList.add(resourceUrl.substring(0, resourceUrl.indexOf(".gif")));
                }else if (resourceUrl.contains("_DURATION")){
                    newUrlList.add(resourceUrl.substring(0, resourceUrl.indexOf("_DURATION")));
                }else {
                    newUrlList.add(resourceUrl);
                }
            }
            if (newUrlList != null && !newUrlList.isEmpty()) {
                AliYunOSSUtil.deleteObjectList(newUrlList);
            }
        }
    }

    @Override
    public void updateCommentAdmin(CommentAdminDTO commentAdminDTO) {
        commentAdminDTO.setAdminer(getOperatorName());
        commentAdminDTO.setOperator(getOperatorName());
        String url = UrlConstant.SERVER_URL + COMMENT_URL;
        String req = JSONObject.toJSONString(commentAdminDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
    }

    private String getOperatorName() {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        return activeUser.getUsername();
    }

    @Override
    public Map<String, Object> getUserTrendSum(Map<String, String> paramMap) {
        String url = UrlConstant.SERVER_URL + TREND_URL + NUMBER_URL;
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        return rspMap;
    }

    @Override
    public Map<String, Object> getUserCommentSum(Map<String, String> paramMap) {
        String url = UrlConstant.SERVER_URL + COMMENT_URL + NUMBER_URL;
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        return rspMap;
    }

    @Override
    public Map<String, Object> getUserLikeSum(Map<String, String> paramMap) {
        String url = UrlConstant.SERVER_URL + LIKE_URL + NUMBER_URL;
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(rsp);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        return rspMap;
    }

    @Override
    public BaseRsp listAllTopTwitter(Map<String, String> paramMap) {
        String url = UrlConstant.SERVER_URL + TWITTER_TOP_URL;
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp baseRsp = JSON.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(baseRsp);
        return baseRsp;
    }

    @Override
    public BaseRsp saveTopTwitter(TwitterTopCfgAdminDTO adminDTO) {
        adminDTO.setOperator(getOperatorName());
        String url = UrlConstant.SERVER_URL + TWITTER_TOP_URL;
        String req = JSON.toJSONString(adminDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp baseRsp = JSON.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(baseRsp);
        return baseRsp;
    }

    @Override
    public BaseRsp deleteTopTwitter(Long id) {
        String url = UrlConstant.SERVER_URL + TWITTER_TOP_URL + "/" + id;
        String body = HttpInvokeUtil.httpDelete(url, null);
        BaseRsp baseRsp = JSON.parseObject(body, BaseRsp.class);
        exceptionService.getFailureResultEnum(baseRsp);
        return baseRsp;
    }
}
